package net.studio.simpletetris.control;

import net.studio.simpletetris.intf.IBlock;
import net.studio.simpletetris.intf.IField;
import net.studio.simpletetris.intf.IGameView;
import android.graphics.Canvas;
import android.view.SurfaceView;

public class AnimateThread extends Thread {
	private IGameView gameView;
	private boolean runFlag = false;
	private int flag = 1;
	private int x = 0;
	private int y = Game.instance.getGameView().getField().getRows() - 1;
	private int color = Figure.getRandomColor();
	
	public AnimateThread(IGameView gameView) {
		this.gameView = gameView;
	}

	public void setRunning(boolean run) {
		runFlag = run;
	}

	@Override
	public void run() {
		Canvas canvas;

		while (runFlag) {

			canvas = null;

			try {
				canvas = ((SurfaceView)gameView).getHolder().lockCanvas(null);
				if (canvas != null) {
					synchronized (((SurfaceView)gameView).getHolder()) {
						if (drawAnimate(gameView, canvas))
							break;
					}
				}
			} finally {
				if (canvas != null) {
					((SurfaceView)gameView).getHolder().unlockCanvasAndPost(canvas);
				}
			}
		}
		
	}
	
	private boolean drawAnimate(IGameView gameView, Canvas canvas) {
		IField field = Game.instance.getGameView().getField();
		if (y < 0) {
			Game.instance.reset();
			return true;
		}
		
		IBlock block = field.addBlock(x, y, color);
		Game.instance.drawBlock(gameView, canvas, block);
		
		x += flag;
		if (x < 0 || x >= field.getCols()) {
			flag = -flag;
			x += flag;
			y--;
		}
		return false;
	}

}
